using UnityEngine;
using System.Collections;
using Prime31;


public class SmoothFollow : MonoBehaviour
{
    //public Transform target;
    public Transform target2;
    public Transform target1;

    public float smoothDampTime = 0.2f;
    public float cameraScaleFactor = 1;
    public float maxCameraScale = 10;
    public float minCameraScale = 4;
    [HideInInspector]
    public new Transform transform;
    public Vector3 cameraOffset;
    public bool useFixedUpdate = false;

    private CharacterController2D _playerController;
    private Vector3 _smoothDampVelocity;
    private Vector3 centerPos;
    private Camera camera;


    void Awake()
    {
        transform = gameObject.transform;
        _playerController = target1.GetComponent<CharacterController2D>();
        camera = gameObject.GetComponent<Camera>();
    }


    void LateUpdate()
    {
        if (!useFixedUpdate)
            updateCameraPosition();
    }


    void FixedUpdate()
    {
        if (useFixedUpdate)
            updateCameraPosition();
    }

    private Vector3 GetBetweenPoint(Vector3 start, Vector3 end, float percent = 0.5f)
    {
        Vector3 normal = (end - start).normalized;
        float distance = Vector3.Distance(start, end);
        return normal * (distance * percent) + start;
    }
    void updateCameraPosition()
    {
        centerPos = GetBetweenPoint(target1.position, target2.position, 0.5f);
        float distance = Vector3.Distance(target1.position, target2.position);
        distance = Mathf.Min(maxCameraScale, Mathf.Max(distance, minCameraScale));
        camera.orthographicSize = cameraScaleFactor * distance;

        if (_playerController == null)
        {
            transform.position = Vector3.SmoothDamp(transform.position, centerPos - cameraOffset, ref _smoothDampVelocity, smoothDampTime);
            return;
        }

        if (_playerController.velocity.x > 0)
        {
            transform.position = Vector3.SmoothDamp(transform.position, centerPos - cameraOffset, ref _smoothDampVelocity, smoothDampTime);
        }
        else
        {
            var leftOffset = cameraOffset;
            leftOffset.x *= -1;
            transform.position = Vector3.SmoothDamp(transform.position, centerPos - leftOffset, ref _smoothDampVelocity, smoothDampTime);
        }
    }

}
